package com.itheima;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SpringApplicationContext {
    private String fileName;
    private Map<String,Object> beanMaps = new HashMap<String, Object>();
    public SpringApplicationContext(String fileName){
        this.fileName = fileName;
        parseXml();
    }

    public void parseXml(){
        try{
            SAXReader saxReader = new SAXReader();
            InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);
            Document xmlDom = saxReader.read(in);
            Element rootElement = xmlDom.getRootElement();
            List<Element> beanList = rootElement.elements();
            if(beanList!=null && beanList.size()>0){
                for (Element bean : beanList) {
                    String id = bean.attributeValue("id");
                    String className = bean.attributeValue("class");
                    Class<?> clz = Class.forName(className);
                    Object obj = clz.newInstance();
                    List<Element> propertyList = bean.elements();
                    if(propertyList!=null && propertyList.size()>0){
                        for (Element property : propertyList) {
                            String name = property.attributeValue("name");
                            Field field = clz.getDeclaredField(name);
                            field.setAccessible(true);
                            String value = property.attributeValue("value");
                            if(value!=null && !"".equals(value)){
                                field.set(obj,value);
                            }
                        }
                    }
                    beanMaps.put(id,obj);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public <T>T getBean(String beanId){
        return (T)beanMaps.get(beanId);
    }
}
